package socketTest.chapter03;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class ToUpperTCPNIOClient {


    public String toUpperRemote(String serverIp, int serverPort, String str) {
        StringBuilder recvStrBuilder = new StringBuilder();
        Socket clientSocket = null;
        try {
            //创建TCP Socket
            clientSocket = new Socket(serverIp,serverPort);

            //写出请求字符串
            OutputStream out = clientSocket.getOutputStream();
            out.write(str.getBytes());
            out.flush();
            clientSocket.shutdownOutput();

            //读取服务器响应
            InputStream in = clientSocket.getInputStream();
            for (int c = in.read(); c >0; c = in.read()) {
                recvStrBuilder.append((char)c);
            }
        } catch (SocketException e1) {
            e1.printStackTrace();
        } catch (UnknownHostException e2) {
            e2.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != clientSocket) {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                clientSocket = null;
            }
        }

        return recvStrBuilder.toString();
    }

    public static void main(String[] args) {
        ToUpperTCPNIOClient client = new ToUpperTCPNIOClient();
        String recvStr = client.toUpperRemote(ToUpperTCPNIOServer.SERVER_IP, ToUpperTCPNIOServer.SERVER_PORT, "aaaAAAbbbBBBcccCCC");
        System.out.println("收到:" + recvStr);
    }
}